package com.study.map.service.impl;

import com.alibaba.fastjson.JSON;
import com.study.map.config.GaodeMapConfig;
import com.study.map.constant.GaodeMapConstants;
import com.study.map.dto.CoordConvertRequest;
import com.study.map.dto.CoordConvertResponse;
import com.study.map.exception.MapServiceException;
import com.study.map.service.ICoordConvertService;
import com.study.map.util.MapHttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 坐标转换服务实现类
 *
 * @author study
 * @date 2025-08-31
 */
@Slf4j
@Service
public class CoordConvertServiceImpl implements ICoordConvertService {

    @Autowired
    private GaodeMapConfig gaodeMapConfig;

    @Autowired
    private MapHttpUtil mapHttpUtil;

    /**
     * 坐标转换：将非高德坐标转换为高德坐标
     *
     * @param request 坐标转换请求参数
     * @return 坐标转换结果
     * @throws MapServiceException 地图服务异常
     */
    @Override
    public CoordConvertResponse coordConvert(CoordConvertRequest request) throws MapServiceException {
        try {
            // 构建请求URL
            String url = gaodeMapConfig.getApiUrl() + "/" + GaodeMapConstants.API_VERSION_V3 + GaodeMapConstants.COORD_CONVERT_URL;

            // 构建请求参数
            Map<String, Object> params = new HashMap<>();
            if (StringUtils.hasText(request.getLocations())) {
                params.put("locations", request.getLocations());
            }
            params.put("coordsys", request.getCoordsys());
            params.put("output", request.getOutput());

            // 发送HTTP请求
            CoordConvertResponse response = mapHttpUtil.doGet(url, params, CoordConvertResponse.class);

            // 解析响应结果
//            CoordConvertResponse response = JSON.parseObject(responseStr, CoordConvertResponse.class);

            // 检查响应状态
            if (!GaodeMapConstants.STATUS_SUCCESS.equals(response.getStatus())) {
                log.error("坐标转换请求失败，状态码: {}, 信息: {}", response.getStatus(), response.getInfo());
                throw new MapServiceException("坐标转换请求失败: " + response.getInfo());
            }

            return response;
        } catch (Exception e) {
            log.error("坐标转换请求异常", e);
            throw new MapServiceException("坐标转换请求异常", e);
        }
    }

    /**
     * 坐标转换：将非高德坐标转换为高德坐标
     *
     * @param locations 需要转换的坐标，经纬度间以","分隔，坐标间以";"分隔
     * @param coordsys 坐标系类型，可选值：gps, baidu, mapbar
     * @return 坐标转换结果
     * @throws MapServiceException 地图服务异常
     */
    @Override
    public CoordConvertResponse coordConvert(String locations, String coordsys) throws MapServiceException {
        CoordConvertRequest request = new CoordConvertRequest();
        request.setLocations(locations);
        request.setCoordsys(coordsys);
        return coordConvert(request);
    }
}